package com.sjgtw.cloud.web.rescueTeam.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sjgtw.cloud.common.core.constant.CacheConstants;
import com.sjgtw.cloud.common.core.utils.DateUtils;
import com.sjgtw.cloud.common.core.utils.SecurityUtils;
import com.sjgtw.cloud.common.core.utils.StringUtils;
import com.sjgtw.cloud.common.core.web.domain.AjaxResult;
import com.sjgtw.cloud.common.redis.service.RedisService;
import com.sjgtw.cloud.service.SystemServerService;
import com.sjgtw.cloud.system.api.model.LoginUser;
import com.sjgtw.cloud.web.rescueTeam.domain.RescueTeam;
import com.sjgtw.cloud.web.rescueTeam.domain.vo.RescueTeamImportVo;
import com.sjgtw.cloud.web.rescueTeam.mapper.RescueTeamMapper;
import com.sjgtw.cloud.web.rescueTeam.service.IRescueTeamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 抢险队伍Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-03-09
 */
@Service
public class RescueTeamServiceImpl implements IRescueTeamService
{
    @Autowired
    private RescueTeamMapper rescueTeamMapper;

    @Autowired
    private SystemServerService systemServerService;

    @Autowired
    private RedisService redisService;

    /**
     * 查询抢险队伍
     * 
     * @param id 抢险队伍主键
     * @return 抢险队伍
     */
    @Override
    public RescueTeam selectRescueTeamById(Long id)
    {
        return rescueTeamMapper.selectRescueTeamById(id);
    }

    /**
     * 查询抢险队伍列表
     * 
     * @param rescueTeam 抢险队伍
     * @return 抢险队伍
     */
    @Override
    public List<Map<String,Object>> selectRescueTeamList(RescueTeam rescueTeam)
    {
        return rescueTeamMapper.selectRescueTeamList(rescueTeam);
    }

    @Override
    public List<RescueTeamImportVo> selectExportRescueTeamList(RescueTeam rescueTeam) {
        return rescueTeamMapper.selectExportRescueTeamList(rescueTeam);
    }

    /**
     * 新增抢险队伍
     * 
     * @param rescueTeam 抢险队伍
     * @return 结果
     */
    @Override
    public int insertRescueTeam(RescueTeam rescueTeam)
    {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        rescueTeam.setCreateBy(user.getUsername());
        rescueTeam.setCreateTime(new Date());
        return rescueTeamMapper.insertRescueTeam(rescueTeam);
    }

    /**
     * 修改抢险队伍
     * 
     * @param rescueTeam 抢险队伍
     * @return 结果
     */
    @Override
    public int updateRescueTeam(RescueTeam rescueTeam)
    {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

         rescueTeam.setUpdateBy(user.getUsername());
        rescueTeam.setUpdateTime(new Date());
        return rescueTeamMapper.updateRescueTeam(rescueTeam);
    }

    /**
     * 批量删除抢险队伍
     * 
     * @param ids 需要删除的抢险队伍主键
     * @return 结果
     */
    @Override
    public int deleteRescueTeamByIds(Long[] ids)
    {
        return rescueTeamMapper.deleteRescueTeamByIds(ids);
    }

    /**
     * 删除抢险队伍信息
     * 
     * @param id 抢险队伍主键
     * @return 结果
     */
    @Override
    public int deleteRescueTeamById(Long id)
    {
        return rescueTeamMapper.deleteRescueTeamById(id);
    }

    @Override
    public List<String> check(List<RescueTeamImportVo> entities) {
        List<String> errors = new ArrayList<>();
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        List<String> userNames = extractAndDeduplicateUserNames(entities);

        AjaxResult userResult = systemServerService.getUserByNames(StringUtils.join(userNames, ","));
        Map<String, Long> userMap = new HashMap<>();
        if (userResult != null) {
            Object object = userResult.get("data");
            if (object != null) {
                JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(object));
                if (!jsonArray.isEmpty()) {
                    for (int i=0; i<jsonArray.size();i++) {
                        JSONObject json = jsonArray.getJSONObject(i);
                        userMap.put(json.getString("userName"), json.getLong("userId"));
                    }
                }
            }
        }


        List<String> deptNames = extractAndDeduplicateNames(entities);
        AjaxResult result = systemServerService.getDeptByNames(StringUtils.join(deptNames, ","));
        Map<String, Long> deptMap = new HashMap<>();
        if (result != null) {
            Object object = result.get("data");
            if (object != null) {
                JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(object));
                if (!jsonArray.isEmpty()) {
                    for (int i=0; i<jsonArray.size();i++) {
                        JSONObject json = jsonArray.getJSONObject(i);
                        deptMap.put(json.getString("deptName"), json.getLong("deptId"));
                    }
                }
            }
        }

        for (RescueTeamImportVo entity : entities) {
            if (StringUtils.isEmpty(entity.getSectionName())) {
                errors.add("序号为" + entity.getNum() + "行数据区段不能为空");
            } else if (deptMap.containsKey(entity.getSectionName())) {
                entity.setSectionId(deptMap.get(entity.getSectionName()));
            } else {
                errors.add("序号为" + entity.getNum() + "行数据区段不存在");
            }

            if (StringUtils.isEmpty(entity.getWorkAreaName())) {
                errors.add("序号为" + entity.getNum() + "行数据工区不能为空");
            } else if (deptMap.containsKey(entity.getWorkAreaName())) {
                entity.setWorkAreaId(deptMap.get(entity.getWorkAreaName()));
            } else {
                errors.add("序号为" + entity.getNum() + "行数据工区不存在");
            }


            if (StringUtils.isEmpty(entity.getDirectorName())) {
                errors.add("序号为" + entity.getNum() + "行数据主任姓名不能为空");
            } else if (userMap.containsKey(entity.getDirectorName())) {
                entity.setDirectorId(userMap.get(entity.getDirectorName()));
            } else {
                errors.add("序号为" + entity.getNum() + "行数据主任姓名不存在");
            }

            if (StringUtils.isEmpty(entity.getDeputyDirectorName())) {
                errors.add("序号为" + entity.getNum() + "行数据副主任姓名不能为空");
            } else if (userMap.containsKey(entity.getDeputyDirectorName())) {
                entity.setDeputyDirectorId(userMap.get(entity.getDeputyDirectorName()));
            } else {
                errors.add("序号为" + entity.getNum() + "行数据副主任姓名不存在");
            }

            if (user != null) {
                entity.setCreateBy(user.getUsername());
            }
            entity.setCreateTime(DateUtils.getNowDate());
        }
        return errors;
    }

    @Override
    public void batchSave(List<RescueTeamImportVo> entities) {
        if (entities != null && entities.size() > 0) {
            if (entities.size() >= 200) {
                int index = 0;
                while (index <= entities.size()) {
                    int last = Math.min(index + 200, entities.size());
                    List<RescueTeamImportVo> temp = entities.subList(index, last );
                    if (temp != null && temp.size() > 0) {
                        rescueTeamMapper.batchSave(temp);
                    }
                    index += 200;
                }
            } else {
                rescueTeamMapper.batchSave(entities);
            }
        }
    }

    private static List<String> extractAndDeduplicateNames(List<RescueTeamImportVo> entities) {
        Set<String> uniqueNamesSet = new HashSet<>();

        for (RescueTeamImportVo entity : entities) {
            uniqueNamesSet.add(entity.getSectionName());
            uniqueNamesSet.add(entity.getWorkAreaName());
        }

        return new ArrayList<>(uniqueNamesSet);
    }

    private static List<String> extractAndDeduplicateUserNames(List<RescueTeamImportVo> entities) {
        Set<String> uniqueNamesSet = new HashSet<>();

        for (RescueTeamImportVo entity : entities) {
            uniqueNamesSet.add(entity.getDirectorName());
            uniqueNamesSet.add(entity.getDeputyDirectorName());
        }

        return new ArrayList<>(uniqueNamesSet);
    }


}
